#!/usr/bin/env node

import { Command } from 'commander';
import { ExtractionTask } from './types';
import extractor from './index';
import * as fs from 'fs';
import * as path from 'path';

const program = new Command();

program
  .name('translation-extractor')
  .description('CLI tool for extracting translations from source files')
  .version('1.0.0');

program
  .command('start')
  .description('Start the translation extraction service')
  .action(async () => {
    try {
      await extractor.start();
      console.log('Service started successfully');
    } catch (error) {
      console.error('Failed to start service:', error);
      process.exit(1);
    }
  });

program
  .command('stop')
  .description('Stop the translation extraction service')
  .action(async () => {
    try {
      await extractor.stop();
      console.log('Service stopped successfully');
    } catch (error) {
      console.error('Failed to stop service:', error);
      process.exit(1);
    }
  });

program
  .command('add-task')
  .description('Add a new translation extraction task')
  .requiredOption('-c, --config <path>', 'Path to task configuration file')
  .action(async options => {
    try {
      const configPath = path.resolve(options.config);
      const configContent = fs.readFileSync(configPath, 'utf-8');
      const task: ExtractionTask = JSON.parse(configContent);

      await extractor.addTask(task);
      console.log('Task added successfully');
    } catch (error) {
      console.error('Failed to add task:', error);
      process.exit(1);
    }
  });

program
  .command('cancel-task')
  .description('Cancel a running translation extraction task')
  .requiredOption('-i, --id <taskId>', 'Task ID to cancel')
  .action(async options => {
    try {
      await extractor.cancelTask(options.id);
      console.log('Task cancelled successfully');
    } catch (error) {
      console.error('Failed to cancel task:', error);
      process.exit(1);
    }
  });

program
  .command('status')
  .description('Get the status of a translation extraction task')
  .requiredOption('-i, --id <taskId>', 'Task ID to check')
  .action(async options => {
    try {
      const status = extractor.getTaskStatus(options.id);
      console.log(`Task status: ${status}`);
    } catch (error) {
      console.error('Failed to get task status:', error);
      process.exit(1);
    }
  });

program.parse();
